﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Aspose.Cells;
using Microsoft.AspNetCore.Mvc;
using SHZY.BaseData.Interfaces;
using SHZY.Common.Core.Manager.Files;
using SHZY.Common.Core.Manager;
using SHZY.DependencyInjection;
using SHZY.DynamicApiController;
using SHZY.Systems.Entitys.System;
using SHZY.Systems.Interfaces.System;
using Spire.Presentation;
using SqlSugar;
using Mapster;
using SHZY.BaseData.Entitys.Dto.DictionaryData;
using SHZY.ClayObject;
using SHZY.Common.Configuration;
using SHZY.Common.Core.Security;
using SHZY.Common.Enum;
using SHZY.Common.Filter;
using SHZY.Common.Models.NPOI;
using SHZY.Common.Security;
using SHZY.DataEncryption;
using SHZY.FriendlyException;
using SHZY.Systems.Entitys.Dto.DictionaryData;
using SHZY.BaseData.Entitys;
using Microsoft.AspNetCore.Http;
using SHZY.BaseData.Entitys.Dto.QmsBaseDefect;
using SHZY.Common.Helper;
using SHZY.BaseData.Entitys.Common.Dto.DictionaryData;

namespace SHZY.BaseData
{
    [ApiDescriptionSettings(Tag = "BaseData", Name = "SupplierClassification", Order = 200)]
    [Route("api/BaseData/[controller]")]
    public class QmsBaseSupplierClassificationService:IQmsBaseSupplierTypeService,IDynamicApiController,ITransient
    {
        /// <summary>
        /// 服务基础仓储.
        /// </summary>
        private readonly ISqlSugarRepository<DictionaryDataEntity> _repository;

        /// <summary>
        /// 多租户事务.
        /// </summary>
        private readonly ITenant _db;

        /// <summary>
        /// 用户管理.
        /// </summary>
        private readonly IUserManager _userManager;

        /// <summary>
        /// 数据字典服务.
        /// </summary>
        private readonly IDictionaryDataService _dictionaryDataService;

        /// <summary>
        /// 文件管理.
        /// </summary>
        private readonly IFileManager _fileManager;

        /// <summary>
        /// 初始化一个<see cref="QmsBaseSupplierTypeService"/>类型的新实例.
        /// </summary>
        public QmsBaseSupplierClassificationService(
          ISqlSugarRepository<DictionaryDataEntity> qmsBaseSupplierTypeRepository,
          ISqlSugarClient context,
          IUserManager userManager,
          IFileManager fileManager,
          IDictionaryDataService dictionaryDataService)
        {
            _repository = qmsBaseSupplierTypeRepository;
            _db = context.AsTenant();
            _userManager = userManager;
            _fileManager = fileManager;
            _dictionaryDataService = dictionaryDataService;

        }

        /// <summary>
        /// 获取供应商分类信息.
        /// </summary>
        /// <param name="id">主键值.</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            return (await _repository.FirstOrDefaultAsync(x => x.Id == id && x.DictionaryTypeId == "450457363690817989")).Adapt<DictionaryDataInfoOutput>();
        }

        /// <summary>
        /// 根据类型获取供应商分类信息.
        /// </summary>
        /// <param name="id">主键值.</param>
        /// <returns></returns>
        [HttpPost("{id}")]
        public async Task<dynamic> GetInfoFy(string id)
        {
            var data = await _repository.AsQueryable().Where(x => x.Id == id && x.DictionaryTypeId == "450457363690817989").ToListAsync();
            return new { list = data.Adapt<List<DictionaryDataInfoOutput>>() };
        }

        /// <summary>
        /// 获取供应商分类信息列表.
        /// </summary>
        /// <param name="input">请求参数.</param>
        /// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> GetList([FromQuery] BaseDictionarydataListQueryInput input)
        {
            var queryable = _repository.Context.Queryable<DictionaryDataEntity>().Where(x => x.DictionaryTypeId == "450457363690817989")
                .WhereIF(!string.IsNullOrEmpty(input.fullName), it => it.FullName.Contains(input.fullName))
                .WhereIF(!string.IsNullOrEmpty(input.enCode), it => it.EnCode.Contains(input.enCode))
                .WhereIF(!string.IsNullOrEmpty(input.keyword), x => x.Id.Contains(input.keyword) || x.FullName.Contains(input.keyword))
                .Where(x => x.DeleteMark == null).OrderByIF(string.IsNullOrEmpty(input.sidx), a => a.Id);
            if (!string.IsNullOrEmpty(input.sidx))
            {
                queryable.OrderBy("sortCode" + " " + input.sort);
            }
            else
            {
                queryable.OrderBy("sortCode" + " " + "desc");
            }

            var data = await queryable.Select(it => new BaseDictionarydataListOutput
            {
                id = it.Id,
                fullName = it.FullName,
                enCode = it.EnCode,
                sortCode = (long)it.SortCode,
                enabledMark = SqlFunc.IIF(it.EnabledMark == 0, "禁用", "正常"),
            }).ToPagedListAsync(input.currentPage, input.pageSize);
            return PageResult<BaseDictionarydataListOutput>.SqlSugarPageResult(data);
        }

        /// <summary>
        /// 新建供应商分类信息.
        /// </summary>
        /// <param name="input">参数.</param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task CreateSupplierClassification([FromBody] DictionaryDataCrInput input)
        {
            if (await _repository.AnyAsync(x => (x.EnCode == input.enCode) && x.DeleteMark == null && x.DictionaryTypeId == "450457363690817989"))
                throw Oops.Oh(ErrorCode.COM1004);
            var entity = input.Adapt<DictionaryDataEntity>();
            entity.Id = SnowflakeIdHelper.NextId();
            var isOk = await _repository.Context.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(m => m.Create()).ExecuteCommandAsync();
            if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1000);
        }
        /// <summary>
        /// 获取供应商分类信息无分页列表.
        /// </summary>
        /// <param name="input">请求参数.</param>
        /// <returns></returns>
        private async Task<dynamic> GetNoPagingList([FromQuery] BaseDictionarydataListQueryInput input)
        {
            return await _repository.Context.Queryable<DictionaryDataEntity>()
                .WhereIF(!string.IsNullOrEmpty(input.fullName), it => it.FullName.Contains(input.fullName)).Where(x => x.DictionaryTypeId == "450457363690817989")
                .WhereIF(!string.IsNullOrEmpty(input.enCode), it => it.EnCode.Contains(input.enCode))
                .WhereIF(!string.IsNullOrEmpty(input.keyword), it => it.FullName.Contains(input.keyword) || it.EnCode.Contains(input.keyword))
                .OrderByIF(string.IsNullOrEmpty(input.sidx), it => it.Id)
                .Select(it => new BaseDictionarydataListOutput
                {
                    fullName = it.FullName,
                    enCode = it.EnCode,
                    sortCode = (long)it.SortCode,
                    enabledMark = SqlFunc.IIF(it.EnabledMark == 0, "禁用", "正常"),
                }).OrderByIF(!string.IsNullOrEmpty(input.sidx), it => input.sidx + " " + input.sort).ToListAsync();
        }

        /// <summary>
        /// 导出供应商分类信息.
        /// </summary>
        /// <param name="input">请求参数.</param>
        /// <returns></returns>
        [HttpGet("Actions/Export")]
        public async Task<dynamic> Export([FromQuery] BaseDictionarydataListQueryInput input)
        {
            var exportData = new List<BaseDictionarydataListOutput>();
            if (input.dataType == 0)
                exportData = Clay.Object(await GetList(input)).Solidify<PageResult<BaseDictionarydataListOutput>>().list;
            else
                exportData = await GetNoPagingList(input);
            List<ParamsModel> paramList = "[{\"value\":\"供应商分类名称\",\"field\":\"fullName\"},{\"value\":\"供应商分类编码\",\"field\":\"enCode\"},{\"value\":\"排序\",\"field\":\"sortCode\"},{\"value\":\"有效标志\",\"field\":\"enabledMark\"}]".ToList<ParamsModel>();
            ExcelConfig excelconfig = new ExcelConfig();
            excelconfig.FileName = "供应商分类信息.xls";
            excelconfig.HeadFont = "微软雅黑";
            excelconfig.HeadPoint = 10;
            excelconfig.IsAllSizeColumn = true;
            excelconfig.ColumnModel = new List<ExcelColumnModel>();
            foreach (var item in input.selectKey.Split(',').ToList())
            {
                var isExist = paramList.Find(p => p.field == item);
                if (isExist != null)
                    excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value, Width = 25 });
            }

            var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
            ExcelExportHelper<BaseDictionarydataListOutput>.Export(exportData, excelconfig, addPath);
            var fileName = _userManager.UserId + "|" + addPath + "|xls";
            return new
            {
                name = excelconfig.FileName,
                url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "SHZY")
            };
        }

        /// <summary>
        /// 批量删除供应商分类信息.
        /// </summary>
        /// <param name="ids">主键数组.</param>
        /// <returns></returns>
        [HttpPost("batchRemove")]
        public async Task delupdateSupplierClassificationBatch([FromBody] List<string> ids)
        {
            var entitys = await _repository.Context.Queryable<DictionaryDataEntity>().In(it => it.Id, ids).ToListAsync();
            if (entitys.Count > 0)
            {
                try
                {
                    // 开启事务
                    _db.BeginTran();

                    // 批量删除供应商类型
                    var isOk = await _repository.Context.Updateable<DictionaryDataEntity>().SetColumns(it => new DictionaryDataEntity()
                    {
                        DeleteTime = DateTime.Now,
                        DeleteMark = 1,
                        DeleteUserId = _userManager.UserId
                    }).Where(it => ids.Contains(it.Id)).ExecuteCommandHasChangeAsync();
                    // 关闭事务
                    _db.CommitTran();
                }
                catch (Exception)
                {
                    // 回滚事务
                    _db.RollbackTran();

                    throw Oops.Oh(ErrorCode.COM1002);
                }
            }
        }

        /// <summary>
        /// 更新供应商分类信息
        /// </summary>
        /// <param name="id">主键值.</param>
        /// <param name="input">参数.</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task updateSupplierClassification(string id, [FromBody] DictionaryDataUpInput input)
        {
            if (await _repository.AnyAsync(x => (x.EnCode == input.enCode) && x.DeleteMark == null && x.Id != input.id&&x.DictionaryTypeId== "450457363690817989"))
                throw Oops.Oh(ErrorCode.COM1004);
            var entity = input.Adapt<DictionaryDataEntity>();
            var isOk = await _repository.Context.Updateable(entity).UpdateColumns(it => new
            {
                it.Id,
                it.ParentId,
                it.FullName,
                it.EnCode,
                it.Description,
                it.SortCode,
                it.EnabledMark,
            }).CallEntityMethod(m => m.LastModify()).ExecuteCommandHasChangeAsync();
            if (!isOk) throw Oops.Oh(ErrorCode.COM1001);
        }

        /// <summary>
        /// 删除供应商分类信息
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task deleteSupplierType(string id)
        {
            var isOk = await _repository.Context.Updateable<DictionaryDataEntity>().SetColumns(it => new DictionaryDataEntity()
            {
                DeleteTime = DateTime.Now,
                DeleteMark = 1,
                DeleteUserId = _userManager.UserId
            }).Where(x => x.Id == id).ExecuteCommandHasChangeAsync();
            if (!isOk)
                throw Oops.Oh(ErrorCode.COM1002);
        }

        /// <summary>
        /// 上传文件.
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost("Uploader")]
        public async Task<dynamic> Uploader(IFormFile file)
        {
            try
            {
                var _filePath = _fileManager.GetPathByType(string.Empty);
                var _fileName = DateTime.Now.ToString("yyyyMMdd") + "_" + SnowflakeIdHelper.NextId() + Path.GetExtension(file.FileName);
                var stream = file.OpenReadStream();
                await _fileManager.UploadFileByType(stream, _filePath, _fileName);
                return new { name = _fileName, url = string.Format("/api/File/Image/{0}/{1}", string.Empty, _fileName) };

            }
            catch (Exception)
            {
                throw Oops.Oh(ErrorCode.D8001);
            }
        }

        /// <summary>
        /// 导入数据.
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        [HttpPost("ImportData")]
        public async Task<dynamic> ImportData([FromBody] BaseDictionarydataInput input)
        {

            var output = new BaseDictionarydataImportDataOutput();
            foreach (var item in input.list)
            {
                try
                {
                    if (await _repository.AnyAsync(x => (x.EnCode == item.enCode) && x.DeleteMark == null && x.DictionaryTypeId == "450457363690817989"))
                        throw Oops.Oh(ErrorCode.COM1004);

                    if (!string.IsNullOrEmpty(item.sortCode))
                    {
                        System.Text.RegularExpressions.Regex regex = new
                        System.Text.RegularExpressions.Regex(@"^[0-9]\d*$");
                        if (!regex.IsMatch(item.sortCode.ToString()))
                        {
                            item.exceptionMsg = "排序应该为整数！";
                            output.failResult.Add(item);
                            output.fnum++;
                            continue;
                        }
                    }

                    var entity = item.Adapt<DictionaryDataEntity>();

                    //验证参数信息
                    if (string.IsNullOrEmpty(entity.FullName))
                    {
                        item.exceptionMsg = "请输入供应商分类名称！";
                        output.failResult.Add(item);
                        output.fnum++;
                        continue;
                    }
                    if (string.IsNullOrEmpty(entity.EnCode))
                    {
                        item.exceptionMsg = "请输入供应商分类编码！";
                        output.failResult.Add(item);
                        output.fnum++;
                        continue;
                    }
                    if (!string.IsNullOrEmpty(entity.Description))
                    {
                        if (entity.Description.Trim().Length > 500)
                        {
                            item.exceptionMsg = "说明长度不能超过500字！";
                            output.failResult.Add(item);
                            output.fnum++;
                            continue;
                        }
                    }


                    entity.DictionaryTypeId = "450457363690817989";
                    entity.ParentId = "0";
                    entity.EnabledMark = 1;
                    var isOK = await _repository.Context.Insertable(entity).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
                    if (isOK < 1)
                    {
                        output.failResult.Add(item);
                        output.fnum++;
                    }
                    else
                    {
                        output.snum++;
                    }
                }
                catch (Exception ex)
                {
                    item.exceptionMsg = ex.Message;
                    output.failResult.Add(item);
                    output.fnum++;
                }
            }
            if (output.snum == input.list.Count)
            {
                output.resultType = 1;
            }
            else
            {
                output.resultType = 0;
            }
            return output;
        }

        /// <summary>
        /// 模板下载.
        /// </summary>
        /// <returns></returns>
        [HttpGet("TemplateDownload")]
        public async Task<dynamic> TemplateDownload()
        {
            string _fileName = "供应商分类模板.xlsx";
            var filePath = Path.Combine(FileVariable.TemplateFilePath, "supplierClassification_import_template.xlsx"); // 模板路径
            var addFilePath = Path.Combine(FileVariable.TemplateFilePath, _fileName); // 保存路径
            if (!(await _fileManager.ExistsFile(addFilePath)))
            {
                var stream = await _fileManager.GetFileStream(filePath);
                await _fileManager.UploadFileByType(stream, FileVariable.TemporaryFilePath, _fileName);
            }

            return new { name = _fileName, url = "/api/file/Download?encryption=" + DESCEncryption.Encrypt(_userManager.UserId + "|" + _fileName, "SHZY") };
        }

        /// <summary>
        /// 导入预览.
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        [HttpGet("ImportPreview")]
        public async Task<dynamic> ImportPreview(string fileName)
        {
            try
            {
                var filePath = FileVariable.TemporaryFilePath;
                var savePath = Path.Combine(filePath, fileName);
                // 得到数据
                var sr = await _fileManager.GetFileStream(savePath);
                var excelData = ExcelImportHelper.ToDataTable(savePath, sr);
                foreach (var item in excelData.Columns)
                {
                    excelData.Columns[item.ToString()].ColumnName = GetFileEncode(item.ToString());
                }
                // 删除文件
                await _fileManager.DeleteFile(savePath);
                // 返回结果
                return new { dataRow = excelData };
            }
            catch (Exception)
            {

                throw Oops.Oh(ErrorCode.D1801);
            }
        }

        #region PrivateMethod
        private string GetFileEncode(string filed)
        {
            switch (filed)
            {
                case "供应商分类名称":
                    return "fullName";
                case "供应商分类编码":
                    return "enCode";
                case "排序":
                    return "sortCode";
                case "说明":
                    return "description";
                default:
                    return string.Empty;
            }
        }
        #endregion

    }
}
